﻿using DevelopTool.Bll.AssemblyyBlls;
using DevelopTool.Bll.ChatBlls;
using DevelopTool.Bll.LocalDbBlls;
using DevelopTool.Common;
using DevelopTool.Forms.BaseForms;
using DevelopTool.Forms.CommonForms;
using DevelopTool.Forms.CommonHelpers;
using DevelopTool.Forms.LodingForm;
using DevelopTool.Model.CommonModels;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace DevelopTool.Forms
{
    /// <summary>
    /// 选项窗体
    /// </summary>
    public partial class OptionForm : BaseUIForm
    {
        public OptionForm()
        {
            InitializeComponent();
        }


        private void OptionForm_Load(object sender, EventArgs e)
        {

            #region 锁屏时间
            upDownLockScreenTime.Value = Setting.System.LockScreen_Time;
            #endregion

            #region 开机自启动
            bool isAutoStrat = WindowsHelper.IsAutoStrat();
            this.swcStartWithSystem.Active = isAutoStrat;
            #endregion

            #region 窗口关闭方式
            switch (Setting.System.WindowsCloseType)
            {
                case 1:
                    rdoWindowsClose_Type_1.Checked = true;
                    break;
                case 2:
                    rdoWindowsClose_Type_2.Checked = true;
                    break;
            }
            #endregion

            #region 自启动时窗口显示方式
            this.cboAutoStartWindowMini.Checked = Setting.System.AutoStartWindowMini;
            #endregion

            #region 截图快捷键
            this.btnScreenShotHotKey.Text = HotKeyHelper.GetWinfromHotKeyIntoShow(Setting.ScreenShot.HotKey);
            this.btnAuxiliaryInputStart.Text = HotKeyHelper.GetWinfromHotKeyIntoShow(Setting.AuxiliaryInput.StartHotKey);
            #endregion 截图快捷键

            #region 推送消息的模块
            List<string> modules = new List<string>();
            foreach (TreeNode item in cboSendMsgModule.Nodes)
            {
                if (Setting.System.SendMsgModule.Contains(item.Tag.ToString()))
                {
                    item.Checked = true;
                    modules.Add(item.Text);
                }
            }
            cboSendMsgModule.Text = string.Join(";", modules);
            #endregion 推送消息的模块

            #region 右键菜单关联

            foreach (UICheckBox checkBox in this.grpSystemContextMenu_File.GetControls<UICheckBox>(true))
            {
                checkBox.Text = $"使用 {GlobalData.AppName_zh} " + checkBox.Text;
                checkBox.Checked = SystemContextMenuHelper.IsFileTypeAssociationExists("*", checkBox.Name);
            }

            foreach (UICheckBox checkBox in this.grpSystemContextMenu_Folder.GetControls<UICheckBox>(true))
            {
                checkBox.Text = $"{GlobalData.AppName_zh} " + checkBox.Text;
                checkBox.Checked = SystemContextMenuHelper.IsFolderTypeAssociationExists(checkBox.Name);
            }

            #endregion 右键菜单关联

            #region 插件管理

            LaodPluginsMenus();//加载插件列表

            #endregion 插件管理

            #region 局域网聊天

            this.swcChatEnable.Active = ChatNetworkBll.CheckChatServiceRunningState();

            this.cboAutoStartChatMainWindow.Checked = Setting.Chat.AutoStartChatMainWindow;
            this.txtChatPort.Text = Setting.Chat.Port.ToString();
            this.cboChatNotifyAudio.Checked = Setting.Chat.NotifyAudio;
            this.cboChatNotifyPop.Checked = Setting.Chat.NotifyPop;
            #endregion 局域网聊天

            #region 其它设置
            //自动登录
            this.cboAutoLoging.Checked = Setting.System.AutoLoging;
            #endregion 其它设置

            #region 接口设置
            //飞书消息地址
            this.txtFeiShuMsgHookAddress.Text = Setting.System.FeiShuMsgHookAddress;
            #endregion 接口设置

            ThemHelper.SetSystemThem(this);//设置主题
        }


        /// <summary>
        /// 锁屏时间修改事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="value"></param>
        private void upDownLockScreenTime_ValueChanged(object sender, int value)
        {
            if (!upDownLockScreenTime.ContainsFocus) return;

            if (upDownLockScreenTime.Value < 1)
            {
                upDownLockScreenTime.Value = 1;
                this.ShowWarningNotifier("锁屏时间最小只能设置为1分钟", false);
                return;
            }
            if (upDownLockScreenTime.Value > 10240)
            {
                upDownLockScreenTime.Value = 10240;
                this.ShowWarningNotifier("最多7天后锁屏不过分吧~", true, 5000);
                return;
            }

            Setting.System.LockScreen_Time = upDownLockScreenTime.Value;
        }


        /// <summary>
        /// 定时任务日志保留天数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="value"></param>
        private void upDownSchedulerLogRetainTime_ValueChanged(object sender, int value)
        {
            if (!upDownSchedulerLogRetainTime.ContainsFocus) return;
            Setting.Scheduler.LogRetain_Time = upDownSchedulerLogRetainTime.Value;
        }


        /// <summary>
        /// 确认修改密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdatePwd_Click(object sender, EventArgs e)
        {
            if (!base.CheckData(textOldPassword, "请输入原密码"))
            {
                textOldPassword.Focus();
                return;
            }
            if (!base.CheckData(textNewPassword1, "请输入新密码"))
            {
                textNewPassword1.Focus();
                return;
            }
            if (!base.CheckData(textNewPassword2, "请重复输入新密码"))
            {
                textNewPassword2.Focus();
                return;
            }
            if (textNewPassword1.Text != textNewPassword2.Text)
            {
                this.ShowWarningTip(textNewPassword2, "两次输入的新密码不一致");
                return;
            }

            Tuple<int, string> tuple = new Tuple<int, string>(-1, "未知");
            LoadingHelper.ShowLoading("正在修改密码", () =>
            {
                tuple = new LocalUserBll().UpdatePassword(textOldPassword.Text, textNewPassword1.Text);//修改密码逻辑
            });


            if (tuple.Item1 == 1)
            {
                this.ShowSuccessNotifier(tuple.Item2);
                Close();
            }
            else if (tuple.Item1 == 0)
            {
                this.ShowErrorNotifier(tuple.Item2);
            }
            else if (tuple.Item1 == 2)
            {
                this.ShowErrorDialog(tuple.Item2);
            }
            else
            {
                this.ShowErrorDialog(tuple.Item2);
            }
        }


        /// <summary>
        /// 清理缓存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClearCache_Click(object sender, EventArgs e)
        {
            string msg = "将会清理以下缓存，请谨慎操作：\n\n1、使用过程中产生的临时文件。\n2、搜索程序集产生的缓存数据。\n\n是否确定清理？";
            if (!this.ShowAskDialog($"{GlobalData.AppName_zh}-敏感操作", msg, UIStyle.Orange, true, UIMessageDialogButtons.Cancel)) return;

            LoadingHelper.ShowLoading("正在清理缓存", () =>
            {
                new AssemblyyBll().ClearCache();//清除程序集缓存

                LiteDbContext.ClearCache();//重新排列数据库空间

                DirectoryHelper.DeleteDir(GlobalData.AppTempDirectory);//清空临时目录
            });
            this.ShowInfoNotifier("缓存清理完成");
        }


        /// <summary>
        /// 开启/取消程序开机自启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void swcStartWithSystem_MouseClick(object sender, MouseEventArgs e)
        {
            bool isSetOk = WindowsHelper.SetAutoStart(this.swcStartWithSystem.Active);

            if (isSetOk)
            {
                if (this.swcStartWithSystem.Active)
                {
                    this.ShowSuccessTip("开启成功");
                }
                else
                {
                    this.ShowSuccessTip("关闭成功");
                }
            }
            else
            {
                if (this.swcStartWithSystem.Active)
                {
                    this.ShowErrorTip("开启失败");
                }
                else
                {
                    this.ShowErrorTip("关闭失败");
                }

                this.swcStartWithSystem.Active = false;
            }
        }


        /// <summary>
        /// 窗口关闭方式 单选选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rdoWindowsClose_Type_MouseClick(object sender, MouseEventArgs e)
        {
            UIRadioButton radioButton = sender as UIRadioButton;
            Setting.System.WindowsCloseType = radioButton.TagString.ToInt();
        }


        /// <summary>
        /// 截图快捷键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnScreenShotHotKey_Click(object sender, EventArgs e)
        {
            ChoiceHotKeyForm choiceHotKeyForm = new ChoiceHotKeyForm
            {
                TitleText = "截图快捷键",
                KeyStr = HotKeyHelper.GetWinfromHotKeyIntoShow(Setting.ScreenShot.HotKey)
            };
            if (choiceHotKeyForm.ShowDialog() == DialogResult.OK)
            {
                HotKeyHelper.UnRegisterGlobalHotKey(GlobalData.MainForm, Setting.ScreenShot.HotKey);//先卸载快捷键
                Setting.ScreenShot.HotKey = choiceHotKeyForm.KeyStr;
                this.btnScreenShotHotKey.Text = HotKeyHelper.GetWinfromHotKeyIntoShow(choiceHotKeyForm.KeyStr);//设置按钮显示
                HotKeyHelper.RegisterGlobalHotKey(GlobalData.MainForm, Setting.ScreenShot.HotKey);//在注册快捷键
            }
        }


        /// <summary>
        /// 辅助输入开始快捷键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAuxiliaryInputStart_Click(object sender, EventArgs e)
        {
            ChoiceHotKeyForm choiceHotKeyForm = new ChoiceHotKeyForm
            {
                TitleText = "辅助输入[开始]快捷键",
                KeyStr = HotKeyHelper.GetWinfromHotKeyIntoShow(Setting.AuxiliaryInput.StartHotKey)
            };
            if (choiceHotKeyForm.ShowDialog() == DialogResult.OK)
            {
                HotKeyHelper.UnRegisterGlobalHotKey(GlobalData.MainForm, Setting.AuxiliaryInput.StartHotKey);//先卸载快捷键
                Setting.AuxiliaryInput.StartHotKey = choiceHotKeyForm.KeyStr;
                this.btnAuxiliaryInputStart.Text = HotKeyHelper.GetWinfromHotKeyIntoShow(choiceHotKeyForm.KeyStr);//设置按钮显示
                HotKeyHelper.RegisterGlobalHotKey(GlobalData.MainForm, Setting.AuxiliaryInput.StartHotKey);//在注册快捷键
            }
        }


        /// <summary>
        /// 自动登录设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboAutoLoging_MouseClick(object sender, MouseEventArgs e)
        {
            if (this.cboAutoLoging.Checked)
            {
                CountDownAskMessageForm countDownAskMessageForm = new CountDownAskMessageForm($"{GlobalData.AppName_zh}-隐私安全风险，冷静期", "开启此功能后可能有泄露隐私的风险，请在信任的环境中启用此功能！", 5);

                if (countDownAskMessageForm.ShowDialog() != DialogResult.OK)
                {
                    this.cboAutoLoging.Checked = false;
                }
            }

            Setting.System.AutoLoging = this.cboAutoLoging.Checked;
        }

        private void cboAutoStartWindowMini_MouseClick(object sender, MouseEventArgs e)
        {
            Setting.System.AutoStartWindowMini = this.cboAutoStartWindowMini.Checked;
        }

        /// <summary>
        /// 飞书消息Hook地址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtFeiShuMsgHookAddress_TextChanged(object sender, EventArgs e)
        {
            Setting.System.FeiShuMsgHookAddress = this.txtFeiShuMsgHookAddress.Text;
        }


        /// <summary>
        /// 推送消息的模块
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboSendMsgModule_TextChanged(object sender, EventArgs e)
        {
            List<string> modules = new List<string>();
            foreach (TreeNode item in cboSendMsgModule.Nodes)
            {
                if (item.Checked)
                    modules.Add(item.Tag.ToString());
            }
            Setting.System.SendMsgModule = modules;
        }

        private void lblFeishuHelper_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            AboutHelper.ShowAbout("配置飞书消息");
        }


        /// <summary>
        /// 系统-文件-右键菜单关联
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboRightClickMenu_File_MouseClick(object sender, MouseEventArgs e)
        {
            if (sender is UICheckBox checkBox)
            {
                if (checkBox.Checked)
                {
                    SystemContextMenuHelper.AddFileTypeAssociation("*", checkBox.Text, checkBox.Name, $"Action=%{checkBox.TagString}");
                }
                else
                {
                    SystemContextMenuHelper.RemoveFileTypeAssociation("*", checkBox.Name);
                }
            }
        }


        /// <summary>
        /// 系统-目录-右键菜单关联
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboRightClickMenu_Folder_MouseClick(object sender, MouseEventArgs e)
        {
            if (sender is UICheckBox checkBox)
            {
                if (checkBox.Checked)
                {
                    SystemContextMenuHelper.AddFolderTypeAssociation(checkBox.Text, checkBox.Name, $"Action=%{checkBox.TagString}");
                }
                else
                {
                    SystemContextMenuHelper.RemoveFolderTypeAssociation(checkBox.Name);
                }
            }
        }

        #region 插件相关

        /// <summary>
        /// 加载（刷新）插件列表
        /// </summary>
        private void LaodPluginsMenus()
        {
            this.navMenuPlugins.ClearAll();

            foreach (PluginsModel pluginsModel in Setting.Plugins.PluginsList)
            {
                TreeNode node = this.navMenuPlugins.CreateNode(pluginsModel.Text, Guid.NewGuid());
                node.Tag = pluginsModel;

                this.navMenuPlugins.AddNodeRightSymbol(node, 560147);
                this.navMenuPlugins.AddNodeRightSymbol(node, 557711);
            }

            //刷新系统菜单（顶部菜单）
            BaseUIForm mainForm = GlobalData.MainForm as BaseUIForm;
            mainForm.ReLoadMenus();
        }


        /// <summary>
        /// 新增插件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddPlugins_Click(object sender, EventArgs e)
        {
            string dllPath = string.Empty;

            if (!Dialogs.OpenFileDialog(ref dllPath, "程序集(动态库)|*.dll")) return;

            if (!AssemblyHelper.IsAssembly(dllPath))
            {
                this.ShowWarningTip(this.btnAddPlugins, "选择的文件不是标准的程序集(动态库)");
                return;
            }

            List<Type> derivedClasses = AssemblyHelper.GetAllDerivedClasses<PluginsForm>(dllPath);

            List<TreeNode> treeNodes = new List<TreeNode>();

            foreach (Type type in derivedClasses)
            {
                if (type.CreateInstance() is PluginsForm pluginsForm)
                {
                    treeNodes.Add(new TreeNode()
                    {
                        Text = pluginsForm.Text,
                        Tag = type.FullName,
                    });
                }
            }

            if (treeNodes.Count <= 0)
            {
                this.ShowWarningTip(this.btnAddPlugins, "未能在程序集中找到扩展插件");
                return;
            }

            using (ComboBoxForm comboBoxForm = new ComboBoxForm($"请选择{GlobalData.AppName_zh}扩展插件", treeNodes, mustBeSelected: true))
            {
                if (comboBoxForm.ShowDialog() != DialogResult.OK) return;

                List<PluginsModel> pluginsModels = Setting.Plugins.PluginsList;

                foreach (TreeNode selectedNode in comboBoxForm.SelectedNodes)
                {
                    if (pluginsModels.Exists(it => it.FullName == selectedNode.Tag.ToString() && it.DllPath == dllPath && it.Text == selectedNode.Text))
                    {
                        this.ShowWarningNotifier($"扩展插件【{selectedNode.Text}】已存在，无需重复选择");
                        continue;
                    }

                    PluginsModel pluginsModel = new PluginsModel()
                    {
                        Text = selectedNode.Text,
                        Id = Guid.NewGuid(),
                        DllPath = dllPath,
                        FullName = selectedNode.Tag.ToString()
                    };

                    pluginsModels.Add(pluginsModel);

                    Setting.Plugins.PluginsList = pluginsModels;

                    LaodPluginsMenus();
                }
            }
        }


        /// <summary>
        /// 插件操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="node"></param>
        /// <param name="index"></param>
        /// <param name="symbol"></param>
        private void navMenuPlugins_NodeRightSymbolClick(object sender, TreeNode node, int index, int symbol)
        {
            PluginsModel pluginsModel = node.Tag as PluginsModel;

            if (symbol == 557711)//删除插件
            {
                if (this.ShowAskDialog("提示", $"是否确定删除扩展插件{Environment.NewLine}【{pluginsModel.Text}】{Environment.NewLine}【{pluginsModel.FullName}】{Environment.NewLine}【{pluginsModel.DllPath}】", UIStyle.Orange, true, UIMessageDialogButtons.Cancel))
                {
                    List<PluginsModel> pluginsModels = Setting.Plugins.PluginsList;

                    pluginsModels.RemoveAll(it => it.Id == pluginsModel.Id);

                    Setting.Plugins.PluginsList = pluginsModels;

                    LaodPluginsMenus();
                }
            }
            else if (symbol == 560147)//打开插件程序集路径
            {
                Dialogs.OpenDir(pluginsModel.DllPath);
            }
        }

        #endregion 插件相关


        #region 局域网聊天

        /// <summary>
        /// 聊天功能是否启用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void swcChatEnable_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                Setting.Chat.Enable = this.swcChatEnable.Active;

                if (this.swcChatEnable.Active)
                {
                    new ChatBll().StartChatService();
                    this.ShowSuccessTip("聊天功能开启成功");
                }
                else
                {
                    ChatNetworkBll.Exit();
                }

                
            }
            catch(Exception ex)
            {
                this.ShowErrorDialog(ex.Message);

                this.swcChatEnable.Active = !this.swcChatEnable.Active;
            }

        }

        /// <summary>
        /// 是否每次启动后打开聊天窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboAutoStartChatMainWindow_MouseClick(object sender, MouseEventArgs e)
        {
            Setting.Chat.AutoStartChatMainWindow = this.cboAutoStartChatMainWindow.Checked;
        }

        /// <summary>
        /// 聊天端口号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtChatPort_TextChanged(object sender, EventArgs e)
        {
            Setting.Chat.Port = Convert.ToInt32(this.txtChatPort.Text);
        }

        /// <summary>
        /// 音频提醒
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboChatNotifyAudio_MouseClick(object sender, MouseEventArgs e)
        {
            Setting.Chat.NotifyAudio = this.cboChatNotifyAudio.Checked;
            ChatBll.NotifyAudio();
        }

        /// <summary>
        /// 右下角弹窗提醒
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboChatNotifyPop_MouseClick(object sender, MouseEventArgs e)
        {
            Setting.Chat.NotifyPop = this.cboChatNotifyPop.Checked;
            ChatBll.NotifyPop($"已开启局域网聊天右下角弹窗提醒");
        }

        #endregion 局域网聊天


    }
}
